# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved. See docs/LICENSE
#
###

__revision__ = '$Hg:$'

# system imports

# DDB imports
from ddb.log import log
from ddb.tools import syntax, NotImplementedException
from ddb.user import userRegister, makeMask
from ddb.settings import USER_FLAG
from ddb.access import access

# system imports
import sets

# DDB exports
EXPORT=['Usermod']

class Usermod:
    _flagDeps = {
        'n':    'n',
        'm':    'n',
        'o':    'mo',
        'f':    'nmo',
        'r':    'nmo',
        }

    _flags = {
        'n':    '(conference) owner',
        'm':    '(conference) manager',
        'o':    '(conference) owner',
        'f':    '(conference) friend',
        'r':    'RSS manager'
        }

    def __init__(self):
        self.callbacks = {}

    @access('nu', 'nu')
    def flag(self, event):
        """<[list]|[set]|[get]|[remove]> <username> [<flag>]

        Set or get the flags for <username> on the conference."""
        action = ''
        if event.args:
            action = event.args.split()[0]
            # be user-friendly
            if action == 'del':
                action = 'remove'
        if len(event.args.split()) not in [1, 2, 3] or not hasattr(self, '_flag_%s' % action):
            return event.reply(syntax())
        call = getattr(self, '_flag_%s' % action)
        call(event)

    def _flag_list(self, event):
        """-

        List the available flags."""
        flags = self._flags.keys()
        flags.sort()
        reply = []
        for flag in flags:
            reply.append('\002%s\002: %s' % (flag, self._flags[flag]))
        event.reply(', '.join(reply))

    @access('nu', 'nu')
    def _flag_set(self, event):
        """<username> <flag(s)> [--global]

        Adds <flag> to the list of flags for the user on the current conference."""
        parts = event.args.split()
        if len(parts) == 4 and parts[-1].lower() == '--global':
            alterGlobal = True
            _, username, flags, _ = parts
        elif len(parts) == 3:
            _, username, flags = parts
            alterGlobal = False
        else:
            return event.reply(syntax().replace('_flag_', 'flag '))
        if not userRegister.userCheck(username):
            return event.reply('User "%s" does not exist.' % username)
        # event.accessFlags contains lists of [global, local] flags
        mayAlter = [False, False]
        for flag in flags:
            if not self._flagDeps.has_key(flag):
                return event.reply('Invalid flag: "%s"' % flag)
            # check needed flags to alter the flags
            needed = self._flagDeps[flag]
            for need in needed:
                for i in [0, 1]:
                    print 'need', need, '<>', event.accessFlags[i]
                    if need in event.accessFlags[i]:
                        mayAlter[i] = True
        if not True in mayAlter:
            return event.reply('You may not set this flag.')
        if alterGlobal and not mayAlter[0]:
            return event.reply('You may not set this global flag.')
        if alterGlobal:
            target = '*'
        else:
            target = ':'.join([event.idx, event.target.lower()])
        userRegister.rightsAdd(username, target, flags)
        event.reply('Updated the flags for %s on %s' % (username, target))

    @access('nmo', 'nmo')
    def meet(self, event):
        """[<identity>]

        Introduce <identity> as a new user to the bot. Only available on
        supported transports."""
        if not hasattr(event.transport, 'meet'):
            return event.reply('This transport does not support the meet command')

    @access('nmo', 'nmo')
    def user(self, event):
        """<[add]|[show]|[remove]> [<username>]

        Manipulate users."""
        action = ''
        if event.args:
            action = event.args.split()[0]
            # be user-friendly
            if action == 'del':
                action = 'remove'
            elif action == 'get':
                action = 'show'
        if len(event.args.split()) not in [1,2] or not hasattr(self, '_user_%s' % action):
            return event.reply(syntax())
        # hack to be user-friendly
        if len(event.args.split()) == 1:
            action = 'show'
            event.args = 'show %s' % event.args
        call = getattr(self, '_user_%s' % action)
        call(event)
        
    @access('nmo', 'nmo')
    def _user_add(self, event):
        """[<username>]

        Add a record for the given <username>."""
        _, username = event.args.split()
        if userRegister.userCheck(username):
            return event.reply('User "%s" already exists.' % username)
        userRegister.add(username, '')
        userRegister.save()
        event.reply('User "%s" added, don\'t forget to add a host(mask) next!' % username)

    @access('nm', 'nm')
    def _user_remove(self, event):
        raise NotImplementedException

    def _user_show(self, event):
        """[<username>]

        Shows information about <username>."""
        _, username = event.args.split()
        return event.reply(str(userRegister.userCheck(username)))


# vim:ts=4:sw=4:et:
